package net.nagaseyasuhito.nicola.component;

import javax.persistence.NoResultException;

import net.nagaseyasuhito.nicola.entity.Entry;
import net.nagaseyasuhito.nicola.entity.User;
import net.nagaseyasuhito.nicola.page.UserPage;
import net.nagaseyasuhito.nicola.service.EntryService;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;

import com.google.inject.Inject;

public class CurrentEntryPanel extends Panel {
	private static final long serialVersionUID = 1L;

	@Inject
	private EntryService entryService;

	private User user;
	
	public CurrentEntryPanel(String id, User user) {
		super(id);
		this.user = user;

		this.add(new Image("image", new NicolaImageResource(this.user.getImage(), 64)));
		
		this.setModel(new CompoundPropertyModel(null));
		
		PageParameters pageParameters = new PageParameters();
		pageParameters.add("name", user.getName());
		this.add(new BookmarkablePageLink("user", UserPage.class, pageParameters).add(new Label("user.name")));
		this.add(new Label("createTimestamp"));
		this.add(new Label("content"));
	}

	@Override
	protected void onBeforeRender() {
		Entry entry = null;
		try {
			entry = this.entryService.findCurrentByUser(this.user);
		}
		catch(NoResultException e) {
			entry = new Entry();
			entry.setUser(this.user);
		}
		this.setModelObject(entry);

		super.onBeforeRender();
	}
}
